/*
 * Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package top.continew.admin.hanfu.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import top.continew.admin.common.util.OssIdClearUtils;
import top.continew.admin.hanfu.core.oss.OSS;
import top.continew.admin.hanfu.domain.My;
import top.continew.admin.hanfu.domain.OssFile;
import top.continew.admin.hanfu.domain.bo.MyBo;
import top.continew.admin.hanfu.domain.dto.MyDto;
import top.continew.admin.hanfu.domain.query.MyQuery;
import top.continew.admin.hanfu.domain.vo.MyVo;
import top.continew.admin.hanfu.mapper.AboutMeMapper;
import top.continew.admin.hanfu.service.IAboutMeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 关于我的service类
 */
@SuppressWarnings({"all"})
@Service
@RequiredArgsConstructor
public class AboutMeServiceImpl extends ServiceImpl<AboutMeMapper, My> implements IAboutMeService {

    //  导入oss类
    private final OSS oss;
    private final AboutMeMapper aboutMeMapper;

    /**
     * 添加配置
     * 
     * @param myDto
     */
    @Transactional
    @Override
    public int addAbout(MyDto myDto) {
        if (aboutMeMapper.getStatus().isEmpty() || myDto.getStatus() != 1) {
            My my = new My();
            BeanUtils.copyProperties(myDto, my);
            //      交给oss去将文件发送到本地
            MultipartFile[] array = myDto.getFile().toArray(new MultipartFile[0]);
            List<OssFile> ossFiles = oss.saveFile("AboutMeImg", myDto.getUpdateBy(), array);

            if (ossFiles.isEmpty()) {
                return 0;
            }

            StringBuilder stringBuilder = new StringBuilder();
            for (OssFile ossFile : ossFiles) {
                stringBuilder.append(ossFile.getOssId() + ",");
            }
            //        删除最后一个,
            stringBuilder.delete(stringBuilder.length() - 1, stringBuilder.length());
            //      添加图片id进去(顺带清除前后的多余符号)
            my.setOssId(OssIdClearUtils.cleanFrontCover(stringBuilder.toString()));
            my.setUpdateTime(LocalDateTime.now());
            boolean save = save(my);
            return 1;
        } else {
            System.out.println("添加失败");
            return 0;
        }
    }

    /**
     * 获取图片集合
     * 
     * @param myQuery
     * @return
     */
    @Override
    public Page<MyVo> condition(MyQuery myQuery) {
        return aboutMeMapper.getHanfuListByCondition(new Page<>(myQuery.getPage(), myQuery.getPageSize()), myQuery);
    }

    @Override
    public int deleteAboutMe(ArrayList<Integer> ids) {
        return removeByIds(ids) ? 1 : 0;
    }

    @Override
    public int updateAboutMe(MyDto myDto) {
        boolean update = lambdaUpdate().set(!myDto.getName().isEmpty(), My::getName, myDto.getName())
            .set(!myDto.getDescription().isEmpty(), My::getDescription, myDto.getDescription())
            .set(!myDto.getBusinessScope().isEmpty(), My::getBusinessScope, myDto.getBusinessScope())
            .set(!myDto.getAddress().isEmpty(), My::getAddress, myDto.getAddress())
            .set(!myDto.getPhone().isEmpty(), My::getPhone, myDto.getPhone())
            .set(My::getStatus, myDto.getStatus())
            .set(My::getUpdateBy, myDto.getUpdateBy())
            .set(My::getUpdateTime, LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
            .eq(My::getId, myDto.getId())
            .update();

        return update ? 1 : 0;
    }

    /**
     *
     * @param myBo
     * @return
     */
    @Override
    public int updateAboutMeImg(MyBo myBo) {
        //先查询原有的文件
        My byId = getById(myBo.getId());

        //旧文件组
        String[] ossId = byId.getOssId().split(",");

        //新文件组
        List<String> newOssId = Arrays.stream(myBo.getOssId().split(",")).toList();

        List<String> collect = new ArrayList<>();

        //求两个数组之间的差集

        // 使用流式处理来计算差集
        Arrays.stream(ossId)
            .filter(oss -> !oss.isEmpty() && !oss.equals(" "))
            .filter(oss -> !newOssId.contains(oss))
            .forEach(collect::add);

        //删除差集
        oss.deleteFiles(collect);

        List<MultipartFile> file = myBo.getFile();

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(myBo.getOssId()).append(",");
        if (file != null && !file.isEmpty()) {

            //            调用oss保存方法
            List<OssFile> MyImg = oss.saveFile("AboutMeImg", myBo.getUpdateBy(), file.toArray(new MultipartFile[] {}));

            for (OssFile ossFile : MyImg) {
                if (!(ossFile.getOssId() != null || ossFile.getOssId().equals(" "))) {
                    continue;
                }
                stringBuilder.append(ossFile.getOssId()).append(",");
            }

            stringBuilder.delete(stringBuilder.length() - 1, stringBuilder.length());

        }

        boolean update = lambdaUpdate().eq(My::getId, myBo.getId())
            .set(!stringBuilder.toString().isEmpty(), My::getOssId, OssIdClearUtils.cleanFrontCover(stringBuilder
                .toString()))
            .set(My::getUpdateBy, myBo.getUpdateBy())
            .set(My::getUpdateTime, LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
            .update();

        return update ? 1 : 0;
    }

    public MyVo getAboutWx() {
        return aboutMeMapper.getAboutWx().get(0);
    }
}
